<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图书购物车系统</title>
    <!-- 引入ElementUI样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!-- 引入Axios -->
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <!-- 引入Vue -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
    <!-- 引入ElementUI -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', Arial, sans-serif;
            background-color: #f5f7fa;
            color: #333;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        .header {
            background: linear-gradient(135deg, #1e5799 0%,#207cca 51%,#2989d8 100%);
            color: white;
            padding: 20px 0;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            margin-bottom: 30px;
            position: sticky;
            top: 0;
            z-index: 1000;
        }
        .header-content {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .logo {
            font-size: 24px;
            font-weight: bold;
            display: flex;
            align-items: center;
        }
        .logo i {
            margin-right: 10px;
            font-size: 28px;
        }
        .nav {
            display: flex;
        }
        .nav-item {
            margin-left: 30px;
            cursor: pointer;
            font-size: 16px;
            transition: color 0.3s;
            padding: 5px 10px;
            border-radius: 4px;
            position: relative;
        }
        .nav-item:hover {
            background-color: rgba(255, 255, 255, 0.1);
        }
        .cart-count {
            position: absolute;
            top: -8px;
            right: -8px;
            background-color: #e74c3c;
            color: white;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            font-size: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .page-title {
            font-size: 24px;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #ebeef5;
            color: #1e5799;
        }
        .book-list {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        .book-card {
            background: white;
            border-radius: 6px;
            overflow: hidden;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            transition: all 0.3s;
            cursor: pointer;
            height: 100%;
            display: flex;
            flex-direction: column;
        }
        .book-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 6px 16px 0 rgba(0, 0, 0, 0.2);
        }
        .book-image {
            width: 100%;
            height: 200px;
            background-color: #f0f2f5;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
        }
        .book-image img {
            max-width: 100%;
            max-height: 100%;
            object-fit: cover;
        }
        .book-info {
            padding: 20px;
            flex-grow: 1;
        }
        .book-title {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 10px;
            color: #303133;
            height: 50px;
            overflow: hidden;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
        }
        .book-price {
            color: #e74c3c;
            font-size: 20px;
            font-weight: bold;
            margin: 10px 0;
        }
        .book-desc {
            color: #606266;
            font-size: 14px;
            height: 63px;
            overflow: hidden;
            display: -webkit-box;
            -webkit-line-clamp: 3;
            -webkit-box-orient: vertical;
        }
        .book-footer {
            padding: 10px 20px;
            background-color: #f5f7fa;
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 12px;
            color: #909399;
        }
        .detail-container {
            background: white;
            border-radius: 6px;
            padding: 30px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }
        .detail-header {
            display: flex;
            margin-bottom: 30px;
        }
        .detail-image {
            width: 300px;
            height: 400px;
            background-color: #f5f7fa;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 30px;
            border-radius: 4px;
            overflow: hidden;
        }
        .detail-image img {
            max-width: 100%;
            max-height: 100%;
        }
        .detail-info {
            flex-grow: 1;
        }
        .detail-title {
            font-size: 28px;
            font-weight: bold;
            margin-bottom: 15px;
            color: #1e5799;
        }
        .detail-price {
            color: #e74c3c;
            font-size: 26px;
            font-weight: bold;
            margin-bottom: 20px;
        }
        .detail-meta {
            margin-bottom: 25px;
        }
        .detail-meta-item {
            margin-bottom: 8px;
            font-size: 16px;
            color: #606266;
        }
        .detail-meta-label {
            display: inline-block;
            width: 120px;
            color: #909399;
        }
        .detail-desc {
            line-height: 1.8;
            color: #606266;
            font-size: 16px;
            margin-bottom: 30px;
        }
        .cart-actions {
            display: flex;
            align-items: center;
            margin-bottom: 20px;
        }
        .quantity-selector {
            margin-right: 20px;
        }
        .back-button {
            margin-top: 30px;
            text-align: center;
        }
        .pagination {
            margin-top: 30px;
            display: flex;
            justify-content: center;
        }
        .footer {
            text-align: center;
            padding: 30px 0;
            color: #909399;
            font-size: 14px;
            margin-top: 50px;
            border-top: 1px solid #ebeef5;
        }
        .loading {
            text-align: center;
            padding: 50px 0;
            font-size: 16px;
            color: #909399;
        }
        .empty {
            text-align: center;
            padding: 50px 0;
            font-size: 16px;
            color: #909399;
        }
        .empty i {
            font-size: 50px;
            color: #c0c4cc;
            margin-bottom: 20px;
        }
        .cart-container {
            background: white;
            border-radius: 6px;
            padding: 30px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }
        .cart-item {
            display: flex;
            padding: 20px 0;
            border-bottom: 1px solid #ebeef5;
        }
        .cart-item-image {
            width: 100px;
            height: 150px;
            background-color: #f5f7fa;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 20px;
            border-radius: 4px;
            overflow: hidden;
        }
        .cart-item-image img {
            max-width: 100%;
            max-height: 100%;
        }
        .cart-item-info {
            flex-grow: 1;
        }
        .cart-item-title {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 10px;
            color: #303133;
        }
        .cart-item-price {
            color: #e74c3c;
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 10px;
        }
        .cart-item-meta {
            color: #909399;
            font-size: 14px;
            margin-bottom: 10px;
        }
        .cart-item-actions {
            display: flex;
            align-items: center;
            margin-top: 10px;
        }
        .cart-summary {
            margin-top: 30px;
            padding: 20px;
            background-color: #f5f7fa;
            border-radius: 6px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .cart-total {
            font-size: 18px;
            font-weight: bold;
        }
        .total-price {
            color: #e74c3c;
            font-size: 24px;
        }
        .cart-buttons {
            display: flex;
            gap: 15px;
        }
        @media (max-width: 768px) {
            .detail-header {
                flex-direction: column;
            }
            .detail-image {
                width: 100%;
                margin-right: 0;
                margin-bottom: 20px;
            }
            .book-list {
                grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
            }
            .cart-item {
                flex-direction: column;
            }
            .cart-item-image {
                width: 100%;
                height: 200px;
                margin-right: 0;
                margin-bottom: 15px;
            }
            .cart-summary {
                flex-direction: column;
                gap: 20px;
                align-items: flex-start;
            }
        }
    </style>
</head>
<body>
<div id="app">
    <!-- 顶部导航 -->
    <div class="header">
        <div class="header-content">
            <div class="logo">
                <i class="el-icon-reading"></i>
                图书购物车系统
            </div>
            <div class="nav">
                <div class="nav-item" @click="showBookList">图书列表</div>
                <div class="nav-item" @click="showCart">
                    购物车
                    <span v-if="cartCount > 0" class="cart-count">{{ cartCount }}</span>
                </div>
            </div>
        </div>
    </div>

    <div class="container">
        <!-- 图书列表页面 -->
        <div v-if="currentPage === 'list'">
            <h1 class="page-title">图书列表</h1>

            <div class="book-list">
                <div v-for="book in paginatedBooks" :key="book.bookId" class="book-card" @click="showBookDetail(book.bookId)">
                    <div class="book-image">
                        <img :src="getBookImage(book.bookImage)" alt="图书封面">
                    </div>
                    <div class="book-info">
                        <div class="book-title">{{ book.bookName }}</div>
                        <div class="book-price">¥{{ book.bookPrice.toFixed(2) }}</div>
                        <div class="book-desc">{{ book.bookDesc }}</div>
                    </div>
                    <div class="book-footer">
                        <div>ID: {{ book.bookId }}</div>
                        <div>{{ book.bookIsDisplay === -1 ? '未上架' : '已上架' }}</div>
                    </div>
                </div>
            </div>

            <div v-if="books.length === 0" class="empty">
                <i class="el-icon-notebook-2"></i>
                <p>暂无图书数据</p>
            </div>

            <div class="pagination">
                <el-pagination
                        background
                        layout="prev, pager, next"
                        :page-size="pageSize"
                        :total="books.length"
                        @current-change="handlePageChange">
                </el-pagination>
            </div>
        </div>

        <!-- 图书详情页面 -->
        <div v-if="currentPage === 'detail'">
            <div class="back-button">
                <el-button type="primary" icon="el-icon-arrow-left" @click="showBookList">返回列表</el-button>
            </div>

            <h1 class="page-title">图书详情</h1>

            <div v-if="currentBook" class="detail-container">
                <div class="detail-header">
                    <div class="detail-image">
                        <img :src="getBookImage(currentBook.bookImage)" alt="图书封面">
                    </div>
                    <div class="detail-info">
                        <h1 class="detail-title">{{ currentBook.bookName }}</h1>
                        <div class="detail-price">¥{{ currentBook.bookPrice.toFixed(2) }}</div>

                        <div class="detail-meta">
                            <div class="detail-meta-item">
                                <span class="detail-meta-label">图书ID：</span>
                                {{ currentBook.bookId }}
                            </div>
                            <div class="detail-meta-item">
                                <span class="detail-meta-label">上架状态：</span>
                                <el-tag :type="currentBook.bookIsDisplay === -1 ? 'danger' : 'success'">
                                    {{ currentBook.bookIsDisplay === -1 ? '未上架' : '已上架' }}
                                </el-tag>
                            </div>
                            <div class="detail-meta-item">
                                <span class="detail-meta-label">创建时间：</span>
                                {{ currentBook.createTime || '暂无信息' }}
                            </div>
                            <div class="detail-meta-item">
                                <span class="detail-meta-label">更新时间：</span>
                                {{ currentBook.updateTime || '暂无信息' }}
                            </div>
                            <div class="detail-meta-item">
                                <span class="detail-meta-label">删除状态：</span>
                                <el-tag :type="currentBook.isDeleted === 0 ? 'success' : 'danger'">
                                    {{ currentBook.isDeleted === 0 ? '未删除' : '已删除' }}
                                </el-tag>
                            </div>
                        </div>

                        <div class="detail-desc">
                            {{ currentBook.bookDesc }}
                        </div>

                        <div class="cart-actions">
                            <div class="quantity-selector">
                                <el-input-number
                                        v-model="quantity"
                                        :min="1"
                                        :max="10"
                                        label="数量">
                                </el-input-number>
                            </div>
                            <el-button
                                    type="success"
                                    icon="el-icon-shopping-cart-full"
                                    @click="addToCart"
                                    :loading="addingToCart">
                                加入购物车
                            </el-button>
                        </div>
                    </div>
                </div>
            </div>

            <div v-else class="loading">
                <i class="el-icon-loading"></i>
                <p>正在加载图书详情...</p>
            </div>
        </div>

        <!-- 购物车页面 -->
        <div v-if="currentPage === 'cart'">
            <div class="back-button">
                <el-button type="primary" icon="el-icon-arrow-left" @click="showBookList">返回列表</el-button>
            </div>

            <h1 class="page-title">我的购物车</h1>

            <div v-if="cartItems.length > 0" class="cart-container">
                <div v-for="item in cartItems" :key="item.carId" class="cart-item">
                    <div class="cart-item-image">
                        <img :src="getBookImage(item.bookImage)" alt="图书封面">
                    </div>
                    <div class="cart-item-info">
                        <div class="cart-item-title">{{ item.bookName }}</div>
                        <div class="cart-item-price">¥{{ (item.bookPrice * item.carCount).toFixed(2) }}</div>
                        <div class="cart-item-meta">
                            <div>单价: ¥{{ item.bookPrice.toFixed(2) }}</div>
                            <div>数量: {{ item.carCount }}</div>
                            <div>添加时间: {{ formatDate(item.createTime) || '未知' }}</div>
                        </div>
                        <div class="cart-item-actions">
                            <el-button
                                    type="danger"
                                    icon="el-icon-delete"
                                    size="small"
                                    @click="removeCartItem(item.carId)">
                                删除
                            </el-button>
                        </div>
                    </div>
                </div>

                <div class="cart-summary">
                    <div class="cart-total">
                        总计: <span class="total-price">¥{{ totalCartPrice.toFixed(2) }}</span>
                    </div>
                    <div class="cart-buttons">
                        <el-button type="info" @click="showBookList">继续购物</el-button>
                        <el-button type="success" @click="checkout">结算订单</el-button>
                    </div>
                </div>
            </div>

            <div v-else class="empty">
                <i class="el-icon-shopping-cart-2"></i>
                <p>购物车空空如也</p>
                <el-button type="primary" @click="showBookList" style="margin-top: 20px;">去挑选图书</el-button>
            </div>
        </div>
    </div>

    <div class="footer">
        © 2023 图书购物车系统 | 前端使用ElementUI+Axios实现
    </div>
</div>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                currentPage: 'list', // 'list', 'detail', 'cart'
                books: [],
                currentBook: null,
                cartItems: [],
                pageSize: 12,
                currentPageNum: 1,
                totalBooks: 0,
                quantity: 1,
                addingToCart: false,
                cartCount: 0,
                userId: "93" // 假设当前用户ID为93
            };
        },
        computed: {
            // 分页后的图书数据
            paginatedBooks() {
                const start = (this.currentPageNum - 1) * this.pageSize;
                const end = start + this.pageSize;
                return this.books.slice(start, end);
            },
            // 购物车总价
            totalCartPrice() {
                return this.cartItems.reduce((total, item) => {
                    return total + (item.bookPrice * item.carCount);
                }, 0);
            }
        },
        mounted() {
            this.fetchBooks();
            this.fetchCartItems();
        },
        methods: {
            // 获取图书列表
            fetchBooks() {
                this.$loading({ fullscreen: true, text: '正在加载图书数据...' });

                axios.get('http://localhost:8081/books/queryBooks')
                    .then(response => {
                        this.books = response.data;
                        this.totalBooks = response.data.length;
                        this.$loading().close();
                    })
                    .catch(error => {
                        console.error('获取图书列表失败:', error);
                        this.$message.error('获取图书列表失败，请稍后重试');
                        this.$loading().close();
                    });
            },

            // 获取图书详情
            fetchBookDetail(bookId) {
                this.$loading({ fullscreen: true, text: '正在加载图书详情...' });

                axios.get(`http://localhost:8081/books/findBookById/${bookId}`)
                    .then(response => {
                        this.currentBook = response.data;
                        this.$loading().close();
                    })
                    .catch(error => {
                        console.error('获取图书详情失败:', error);
                        this.$message.error('获取图书详情失败，请稍后重试');
                        this.$loading().close();
                    });
            },

            // 获取购物车数据
            fetchCartItems() {
                axios.get(`http://localhost:8081/car/getCarByUser/${this.userId}`)
                    .then(response => {
                        this.cartItems = response.data;
                        // 为购物车中的每个商品添加图书信息
                        this.cartItems.forEach(item => {
                            const book = this.books.find(b => b.bookId === item.bookId);
                            if (book) {
                                item.bookName = book.bookName;
                                item.bookPrice = book.bookPrice;
                                item.bookImage = book.bookImage;
                            }
                        });
                        this.cartCount = this.cartItems.reduce((count, item) => count + item.carCount, 0);
                    })
                    .catch(error => {
                        console.error('获取购物车数据失败:', error);
                        this.$message.error('获取购物车数据失败');
                    });
            },

            // 添加商品到购物车
            addToCart() {
                if (!this.currentBook) return;

                this.addingToCart = true;

                const cartItem = {
                    carId: "",
                    bookId: this.currentBook.bookId,
                    carCount: this.quantity,
                    userId: this.userId,
                    createTime: "",
                    updateTime: "",
                    isDeleted: ""
                };

                axios.post('http://localhost:8081/car/addCar', cartItem)
                    .then(response => {
                        this.addingToCart = false;
                        this.$message.success('已添加到购物车');
                        this.fetchCartItems(); // 刷新购物车数据
                    })
                    .catch(error => {
                        console.error('添加到购物车失败:', error);
                        this.$message.error('添加到购物车失败');
                        this.addingToCart = false;
                    });
            },

            // 删除购物车商品
            removeCartItem(carId) {
                this.$confirm('确定要删除该商品吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // 在实际项目中这里应该调用删除接口
                    // 这里模拟删除操作
                    this.cartItems = this.cartItems.filter(item => item.carId !== carId);
                    this.cartCount = this.cartItems.reduce((count, item) => count + item.carCount, 0);
                    this.$message.success('已从购物车移除');
                }).catch(() => {
                    this.$message.info('已取消操作');
                });
            },

            // 结算购物车
            checkout() {
                this.$confirm(`确定要结算吗? 总金额: ¥${this.totalCartPrice.toFixed(2)}`, '确认结算', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'success'
                }).then(() => {
                    // 在实际项目中这里应该调用结算接口
                    this.$message.success('结算成功，订单已生成');
                    // 清空购物车
                    this.cartItems = [];
                    this.cartCount = 0;
                }).catch(() => {
                    this.$message.info('已取消结算');
                });
            },

            // 显示图书详情
            showBookDetail(bookId) {
                this.currentPage = 'detail';
                this.quantity = 1; // 重置数量
                this.fetchBookDetail(bookId);
                window.scrollTo(0, 0);
            },

            // 显示图书列表
            showBookList() {
                this.currentPage = 'list';
                window.scrollTo(0, 0);
            },

            // 显示购物车
            showCart() {
                this.currentPage = 'cart';
                window.scrollTo(0, 0);
            },

            // 处理分页变化
            handlePageChange(page) {
                this.currentPageNum = page;
                window.scrollTo(0, 0);
            },

            // 获取图书图片
            getBookImage(imageName) {
                // 在实际应用中，这里应该返回完整的图片URL
                // 由于示例中只有图片名称，这里使用占位图
                return imageName ? `https://via.placeholder.com/200x280?text=Book+Cover` : 'https://via.placeholder.com/200x280?text=No+Image';
            },

            // 格式化日期
            formatDate(dateString) {
                if (!dateString) return '';
                const date = new Date(dateString);
                return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
            }
        }
    });
</script>
</body>
</html>